package com.wxc.api.admin.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.wxc.api.admin.aop.MyLog;
import com.wxc.api.admin.entity.SysMenu;
import com.wxc.api.admin.service.IFilesService;
import com.wxc.api.admin.service.ISysMenuService;
import com.wxc.common.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 * 文件表 前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2022-05-09
 */
@RestController
@RequestMapping("/api.admin/files")
public class FilesController {

    @Autowired
    private IFilesService filesService;

    @Value("${spring.profiles.active}")
    private String active;

    @Value("${file.staticFolder}")
    private String staticFolder;

    // 文件上传
    @MyLog(value = "文件上传")
    @PostMapping("add")
    @SaCheckPermission(value = "files:add", orRole = "admin")
    public Result add(HttpServletRequest request, MultipartFile file) {
        try {
            // 保存文件
            String uploadedFilePath = saveFile(request, file.getInputStream(), Objects.requireNonNull(file.getOriginalFilename())
                    .substring(file.getOriginalFilename().lastIndexOf(".") + 1));

            if (file.getSize() == 0) {
                return Result.fail("请上传文件");
            }

            filesService.add(file.getOriginalFilename(), file.getSize(), uploadedFilePath, file.getContentType());

        } catch (IOException e) {
            return Result.fail("error-path: /upload/file, message: " + e.getMessage());
        }

        return Result.success();
    }

    /**
     * 保存上传的文件到本地服务器
     *
     * @param request HttpServletRequest
     * @param input   输入流
     * @param ext     文件扩展名
     * @return 文件路径
     * @throws IOException
     */
    public String saveFile(HttpServletRequest request, InputStream input, String ext) throws IOException {

        String realPath = staticFolder;

        if (Objects.equals(active, "dev")) {
            realPath = ResourceUtils.getURL("classpath:").getPath() + "\\static\\upload\\file\\";
            // String realPath = System.getProperty("user.dir") + "\\upload\\";
        }

        // System.out.println(ResourceUtils.getURL("classpath:").getPath());
        // String realPath = System.getProperty("user.dir") + "\\upload\\";
        // String realPath = request.getServletContext().getRealPath("/upload/file/");

        File file = new File(realPath);

       // System.out.println(file.getParentFile());

        if (!file.getParentFile().exists()) { // 目录不存在
            file.mkdirs(); // 创建多级目录
        }

        String fileName = UUID.randomUUID() + "." + ext;
        String filePath = realPath + fileName;
        // 取的文件输出流
        OutputStream out = new FileOutputStream(filePath);
        byte[] data = new byte[2048]; // 缓冲数组2KB
        int len = 0; // 读取字节长度
        while ((len = input.read(data)) != -1) {
            out.write(data, 0, len); // 文件写入磁盘
        }
        if (input != null) {
            input.close();
        }
        out.close();
        return "/static/upload/file/" + fileName;
    }


}
